from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import OrderInfo,Payment
from mall import settings
from .utils import generate_alipay_handler

# Create your views here.


class ALIPaymentView(APIView):

    def get(self,request,order_id):
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          user = user,
                                          status = OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            raise Exception('单号为：%s的订单不存在'%order_id)

        alipay = generate_alipay_handler()

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='订单支付',
            return_url="http://www.meiduo.site:8080/pay_success.html",
        )

        alipay_url = settings.ALIPAY_GATEWAY +'?'+ order_string

        return Response({'alipay_url':alipay_url})


class ALIPayResultView(APIView):

    def put(self,request):
        data = request.query_params.dict()
        signature = data.pop('sign')

        alipay = generate_alipay_handler()
        success = alipay.verify(data, signature)
        if success:
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            Payment.objects.create(
                orderk= OrderInfo.objects.get(order_id=order_id),
                trade_id = trade_id
            )

            OrderInfo.objects.filter(order_id=order_id).update(
                status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
            )
            return Response({'trade_id':trade_id})

        else:
            return Response({"message":'支付失败'})

